// 文件路径: src/stores/auth.js

import { defineStore } from 'pinia'
import { authApi } from '@/api/auth'
import { userApi } from '@/api/user';
import router from '@/router';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    apikey: localStorage.getItem('apikey') || null,
    isAuthenticated: false,
    statusChecked: false
  }),
  getters: {
    // isAdmin 的逻辑是正确的，无需修改
    isAdmin: (state) => state.user?.role === 'admin',
    getApiKey: (state) => state.apikey
  },
  actions: {
    async checkAuthStatus(forceRefresh = false) {
      if (this.statusChecked && !forceRefresh) return;
      try {
        const response = await userApi.getCurrentUser();
        if (response.data?.code === 200 && response.data?.data) {
          this.user = response.data.data;
          this.isAuthenticated = true;

          // 【关键修改】后端用户角色已从 'public' 改为 'user'
          if (this.user.role === 'user' && !this.apikey) {
              await this.fetchApiKey();
          }
        } else {
            this.resetAuth();
        }
      } catch (error) {
        this.resetAuth();
      } finally {
          this.statusChecked = true;
      }
    },

    async login(credentials) {
      this.resetAuth();
      try {
        const response = await authApi.login(credentials);
        const responseData = response.data?.data;
        if (responseData && responseData.user) {
          this.user = responseData.user;
          this.apikey = responseData.api_key;
          this.isAuthenticated = true;
          if (this.apikey) {
            localStorage.setItem('apikey', this.apikey);
          }
        } else {
            throw new Error('登录响应数据格式错误');
        }
      } catch (error) {
         this.resetAuth();
         throw error;
      }
    },

    async register(userData) {
      // register 函数逻辑与角色无关，无需修改
      await authApi.register(userData);
    },

    async logout() {
      try {
        await authApi.logout();
      } catch (error) {
        console.error('Logout API call failed, but clearing state anyway:', error);
      } finally {
        this.resetAuth();
        router.push('/login');
      }
    },

    async fetchApiKey() {
      if (!this.isAuthenticated) return;
      try {
        const response = await userApi.getMyApiKey();
        const responseData = response.data?.data;
        if(responseData && responseData.apikey) {
            this.apikey = responseData.apikey;
            localStorage.setItem('apikey', this.apikey);
        }
      } catch (error) {
        console.error('Failed to fetch API Key:', error);
      }
    },

    resetAuth() {
      this.user = null;
      this.apikey = null;
      this.isAuthenticated = false;
      localStorage.removeItem('apikey');
    }
  }
});